package com.kgc.springboot_shiro.config;

import com.kgc.springboot_shiro.realm.CustomerRealm;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


@Configuration
@Slf4j
public class ShiroConfig {

    // shiroFilter
    @Bean
    public ShiroFilterFactoryBean  shiroFilterFactoryBean(DefaultWebSecurityManager securityManager){
       log.info("=============shiroFilterFactoryBean==============");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //配置系统的受限资源   authc
        //配置系统的公共资源   anon
        HashMap<String, String> map = new HashMap<>();
        map.put("/login.jsp","anon");
        map.put("/user/login","anon");
        map.put("/register.jsp","anon");
        map.put("/user/register","anon");
//        map.put("/**", "authc");

        map.put("/**","user");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
//        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
       shiroFilterFactoryBean.setSecurityManager(securityManager);
        return  shiroFilterFactoryBean;
    }
    //SecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);
        CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
        SimpleCookie remember = new SimpleCookie("remember");
        remember.setMaxAge(60);
        remember.setHttpOnly(true);
        cookieRememberMeManager.setCookie(remember);
        defaultWebSecurityManager.setRememberMeManager(cookieRememberMeManager);
        return defaultWebSecurityManager;
    }

    // realm
    @Bean
    public Realm realm(){
        CustomerRealm customerRealm = new CustomerRealm();
        //设置hashed凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置md5加密
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置散列次数
        credentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(credentialsMatcher);
        return customerRealm;
    }

}
